package util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 对 apache http 组件中部分方法的再次封装
 */
public class HttpClientUtil {

    private final static String JSON_CONTENT_TYPE = "application/json";

    private final static String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";

    private HttpClientUtil() {}

    /**
     * post 请求，参数为 json
     * @param url
     * @param data
     * @return
     */
    public static String postJSON(String url, JSON data) throws IOException {
        return post(url, data.toJSONString(), JSON_CONTENT_TYPE);
    }

    /**
     * post 请求， 模拟表单提交， 参数形如 "a=1&b=2"
     * @param url
     * @param data
     * @return
     */
    public static String postForm(String url, Map<String, String> data) throws IOException {
        StringBuilder formParamsBuilder = new StringBuilder();

        for (Map.Entry<String, String> entry : data.entrySet()) {
            formParamsBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }

        String formData = formParamsBuilder.substring(0, formParamsBuilder.length()-1);// 去掉最后多余的 '&'

        return post(url, formData, FORM_CONTENT_TYPE);
    }

    /**
     * post 请求
     * @param url
     * @param data post参数
     * @param contentType  请求格式
     * @return
     */
    private static String post(String url, String data, String contentType) throws IOException {
        HttpClient client   = HttpClients.createDefault();
        String response = null;

        HttpPost     post = new HttpPost(url);
        StringEntity s    = new StringEntity(data, ContentType.create(contentType, "UTF-8"));

        post.setEntity(s);

        HttpResponse res = client.execute(post);

        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            response = EntityUtils.toString(res.getEntity());
        }

        return response;
    }

    /**
     *
     * @param url 请求地址，get请求的参数也包括在内，形如：http://www.xx.com?a=1&b=2
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {
        HttpClient   client       = HttpClients.createDefault();
        HttpGet      httpGet      = new HttpGet(url);
        HttpResponse httpResponse = client.execute(httpGet);

        return EntityUtils.toString(httpResponse.getEntity());
    }
}